package com.example.mvc_thymeleaf.service;


import com.example.mvc_thymeleaf.model.Orders;
import com.example.mvc_thymeleaf.repository.OrdersRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class OrdersServicelmpl implements OrdersService{
    @Autowired
    private OrdersRepository ordersRepository;

    @Override   //返回所有信息
    public List<Orders> getOrders() {
        return ordersRepository.findAll();
    }

    @Override   //添加信息
    public void saveOrders(Orders orders) {
        this.ordersRepository.save(orders);
    }
    @Override   //通过id查找信息
    public Orders getOrdersById(long id) {
        Optional<Orders> optional = ordersRepository.findById(id);

        Orders orders = null;
        if (optional.isPresent()){
            orders = optional.get();
        }else {
            throw new RuntimeException("找不到订单ID:"+id);
        }
        return orders;
    }
    @Override   //通过byID删除信息
    public void deleteOrdersById(long id) {
        this.ordersRepository.deleteById(id);
    }

    @Override   //通过状态查询信息
    public List<Orders> findByStatus(String status) {
        return ordersRepository.findByStatus(status);
    }

    @Override   //排序分页
    public Page<Orders> findPaginated(int pageNo, int pageSize, String sortField, String sortDirection) {
        Sort sort = sortDirection.equalsIgnoreCase(Sort.Direction.ASC.name())
                ? Sort.by(sortField).ascending()
                : Sort.by(sortField).descending();

        //根据页号/每页记录数/排序依据返回某指定页面数据。
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, sort);
        return this.ordersRepository.findAll(pageable);
    }
}
